import { request } from '@/utils/request'
import type { StateOption } from '@/types/state'
import type { ApiResponse } from '@/types/api'

export interface StateResponse {
  id: string
  name: string
  code: string
  module_type: string
  description?: string
  color: string
  icon?: string
  sort_order: number
  is_enabled: boolean
  is_visible: boolean
  is_default: boolean
  created_at?: string
  updated_at?: string
}

export interface StateCreateRequest {
  name: string
  code: string
  module_type: string
  description?: string
  color?: string
  icon?: string
  sort_order?: number
  is_enabled?: boolean
  is_visible?: boolean
  is_default?: boolean
}

export interface StateUpdateRequest {
  name?: string
  code?: string
  description?: string
  color?: string
  icon?: string
  sort_order?: number
  is_enabled?: boolean
  is_visible?: boolean
  is_default?: boolean
}

export class StateAPI {
  /**
   * 获取状态列表
   */
  static async getStates(params?: {
    module_type?: string
    is_enabled?: boolean
    is_visible?: boolean
    search?: string
    skip?: number
    limit?: number
  }) {
    return request.get<StateResponse[]>('/states/', { params })
  }

  /**
   * 获取状态详情
   */
  static async getState(id: string) {
    return request.get<StateResponse>(`/states/${id}`)
  }

  /**
   * 创建状态
   */
  static async createState(data: StateCreateRequest) {
    return request.post<StateResponse>('/states/', data)
  }

  /**
   * 更新状态
   */
  static async updateState(id: string, data: StateUpdateRequest): Promise<StateResponse> {
    try {
      const response = await request.put<ApiResponse<StateResponse>>(`/states/${id}`, data)
      // 处理统一API响应格式
      if (response.data && typeof response.data === 'object') {
        if ('success' in response.data) {
          if (response.data.success && 'data' in response.data && response.data.data) {
            // 成功响应：{ success: true, data: {...} }
            return response.data.data as StateResponse
          } else if (!response.data.success && 'message' in response.data) {
            // 错误响应：{ success: false, message: "..." }
            const error = new Error(response.data.message || '更新状态失败')
            ;(error as any).response = { data: response.data }
            throw error
          }
        } else if ('id' in response.data) {
          // 直接是状态对象
          return response.data as StateResponse
        }
      }
      throw new Error('无效的响应格式')
    } catch (error: any) {
      // 如果是后端返回的错误，保持原有错误对象以便前端提取消息
      if (error.response?.data?.message) {
        const backendError = new Error(error.response.data.message)
        ;(backendError as any).response = error.response
        throw backendError
      }
      throw error
    }
  }

  /**
   * 删除状态
   */
  static async deleteState(id: string, force: boolean = false) {
    return request.delete(`/states/${id}`, {
      params: { force }
    })
  }

  /**
   * 获取模块状态
   */
  static async getModuleStates(moduleType: string, forceRefresh = false) {
    return request.get<StateResponse[]>(`/states/module/${moduleType}`, {
      params: { force_refresh: forceRefresh }
    })
  }

  /**
   * 获取模块状态选项
   */
  static async getModuleStateOptions(moduleType: string) {
    return request.get<StateOption[]>(`/states/module/${moduleType}/options`)
  }

  /**
   * 验证状态代码
   */
  static async validateStateCode(moduleType: string, code: string) {
    return request.get<{ is_valid: boolean }>(`/states/module/${moduleType}/validate/${code}`)
  }

  /**
   * 获取默认状态
   */
  static async getDefaultState(moduleType: string) {
    return request.get<StateResponse>(`/states/module/${moduleType}/default`)
  }

  /**
   * 初始化模块状态
   */
  static async initModuleStates(moduleType: string) {
    return request.post<{
      created: StateResponse[]
      updated: StateResponse[]
      disabled: string[]
      created_count: number
      updated_count: number
      disabled_count: number
    }>(`/states/module/${moduleType}/init`)
  }

  /**
   * 生成TypeScript类型定义
   */
  static async generateTypescriptTypes() {
    return request.get<{ content: string }>('/states/types/generate')
  }

  /**
   * 清除缓存
   */
  static async invalidateCache(moduleType?: string) {
    return request.post<{ invalidated: boolean }>('/states/cache/invalidate', {
      module_type: moduleType
    })
  }

  /**
   * 批量更新状态排序顺序
   */
  static async batchUpdateSortOrder(updates: Array<{ id: string; sort_order: number }>) {
    const response = await request.patch<ApiResponse<{ updated_count: number }>>('/states/batch-sort', updates)
    // 处理统一API响应格式
    if (response.data && typeof response.data === 'object') {
      if ('success' in response.data && 'data' in response.data) {
        // 统一API响应格式：{ success: true, data: {...} }
        return response.data.data
      } else if ('updated_count' in response.data) {
        // 直接是更新结果
        return response.data as { updated_count: number }
      }
    }
    throw new Error('无效的响应格式')
  }

  /**
   * 批量删除状态
   */
  static async batchDeleteStates(stateIds: string[], force: boolean = false) {
    type BatchDeleteResult = {
      deleted_count: number
      skipped_count: number
      errors: string[]
      deleted_ids: string[]
      skipped_ids: string[]
      warnings?: Array<{
        state_id: string
        state_name: string
        warning: string
        data_count: number
        module_name: string
      }>
    }
    
    const response = await request.delete<ApiResponse<BatchDeleteResult>>('/states/batch', {
      data: { 
        state_ids: stateIds,
        force
      }
    })
    
    // 处理统一API响应格式
    if (response.data && typeof response.data === 'object') {
      if ('success' in response.data && 'data' in response.data) {
        // 统一API响应格式：{ success: true, data: {...} }
        return response.data.data as BatchDeleteResult
      } else if ('deleted_count' in response.data && 'skipped_count' in response.data) {
        // 直接是删除结果
        return response.data as unknown as BatchDeleteResult
      }
    }
    throw new Error('无效的响应格式')
  }
}

// 状态转换相关接口
export interface StateTransition {
  id: string
  from_state_id: string
  to_state_id: string
  name: string
  description?: string
  conditions?: any
  actions?: any
  is_enabled: boolean
  created_at?: string
  updated_at?: string
}

export interface StateTransitionCreate {
  from_state_id: string
  to_state_id: string
  name: string
  description?: string
  conditions?: any
  actions?: any
  is_enabled?: boolean
}

export interface StateTransitionUpdate {
  from_state_id?: string
  to_state_id?: string
  name?: string
  description?: string
  conditions?: any
  actions?: any
  is_enabled?: boolean
}

// 状态转换 API 类
export class StateTransitionAPI {
  /**
   * 获取状态转换列表
   */
  static async getTransitions(params?: {
    module_type?: string
    from_state_id?: string
    to_state_id?: string
    is_enabled?: boolean
  }) {
    return request.get<StateTransition[]>('/state-transitions/', { params })
  }

  /**
   * 获取状态转换详情
   */
  static async getTransition(id: string) {
    return request.get<StateTransition>(`/state-transitions/${id}`)
  }

  /**
   * 创建状态转换
   */
  static async createTransition(data: StateTransitionCreate) {
    return request.post<StateTransition>('/state-transitions/', data)
  }

  /**
   * 更新状态转换
   */
  static async updateTransition(id: string, data: StateTransitionUpdate) {
    return request.put<StateTransition>(`/state-transitions/${id}`, data)
  }

  /**
   * 删除状态转换
   */
  static async deleteTransition(id: string) {
    return request.delete(`/state-transitions/${id}`)
  }

  /**
   * 获取可用的状态转换
   */
  static async getAvailableTransitions(fromStateId: string) {
    return request.get<StateTransition[]>(`/state-transitions/from/${fromStateId}`)
  }
}

// 导出兼容性函数
export const getStates = StateAPI.getStates
export const refreshStateCache = StateAPI.invalidateCache
export const stateTransitionApi = StateTransitionAPI